package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/list", name = "进入合同下货物列表")
    public String list(String contractId, @RequestParam(name = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(name = "pageSize", defaultValue = "10")Integer pageSize) {
        //请求域中需要:  1.所有厂家  2.所有货物
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findAll(example, pageNum, pageSize);
        request.setAttribute("page", pageInfo);
        request.setAttribute("contractId", contractId);

        return "/cargo/product/product-list";
    }

    @RequestMapping(value = "/edit",name = "保存货物")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        //完成七牛云上传，返回url 保存到货物图片属性上
        String upload = null;
        try {
            if(productPhoto!=null){
                upload = fileUploadUtil.upload(productPhoto);
            }
        } catch (Exception e) {
            upload = null;
            System.out.println(e.getMessage());
        }
        contractProduct.setProductImage(upload);

        //判断新增或修改
        if (StringUtils.isEmpty(contractProduct.getId())){
            //设置id
            contractProduct.setId(UUID.randomUUID().toString());

            //设置CompanyId ,CompanyName
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProduct.setCreateTime(new Date());
            contractProductService.save(contractProduct);
        }else {
            contractProductService.update(contractProduct);
        }

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    @RequestMapping(value = "/toUpdate",name = "进入合同下货物修改页面")
    public String toUpdate(String id){
        //回显 所有厂家  货物信息
        //查询所有的厂家列表
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria1 = factoryExample.createCriteria();
        criteria1.andCtypeEqualTo("货物");
        List factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        return "/cargo/product/product-update";
    }

    @RequestMapping(value = "/delete",name = "删除货物方法")
    public String delete(String contractId,String id){
        contractProductService.delete(id);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    @RequestMapping(value = "/toImport",name = "跳转到上传货物页面")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import"; //跳转到上传货物页面
    }

    @RequestMapping(value="/import" ,name="上传购销合同货物方法")
    public String importXls(String contractId,MultipartFile file) throws Exception {
        //        1、创建一个的工作薄
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
//        2、获取一个工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        int lastRowIndex = sheet.getLastRowNum(); //读取sheet的最后一行索引值
//        生产厂家	货号	数量	包装单位(PCS/SETS)	装率	箱数	单价	货物描述	要求
        List<ContractProduct> list = new ArrayList<>(); //准备接收所有的需要保存的货物对象 一次性提交事务
        for (int i = 1; i <= lastRowIndex; i++) {
            XSSFRow row = sheet.getRow(i);  //获取行
            ContractProduct product = new ContractProduct(); //货物
            String factoryName = row.getCell(1).getStringCellValue();//生产厂家
            product.setFactoryName(factoryName);
            String productNo = row.getCell(2).getStringCellValue();//货号
            product.setProductNo(productNo);
            Integer cnumber = ((Double) row.getCell(3).getNumericCellValue()).intValue();//数量
            product.setCnumber(cnumber);
            String packingUnit = row.getCell(4).getStringCellValue();//包装单位(PCS/SETS)
            product.setPackingUnit(packingUnit);
            String loadingRate = row.getCell(5).getNumericCellValue() + ""; //装率
            product.setLoadingRate(loadingRate);
            Integer boxNum = ((Double) row.getCell(6).getNumericCellValue()).intValue();//数量
            product.setBoxNum(boxNum);
            Double price = row.getCell(7).getNumericCellValue(); //单价
            product.setPrice(price);
            String productDesc = row.getCell(8).getStringCellValue(); // 货物描述
            product.setProductDesc(productDesc);
            String productRequest = row.getCell(9).getStringCellValue(); // 要求
            product.setProductRequest(productRequest);
            product.setContractId(contractId); // 设置合同id

            //        新增时需要赋id
            product.setCompanyId(getCompanyId());
            product.setCompanyName(getCompanyName());
            product.setId(UUID.randomUUID().toString());  //id 赋值成一个随机id

            product.setCreateDept(getUser().getDeptId());
            product.setCreateBy(getUser().getId());
            product.setCreateTime(new Date());

//            contractProductService.save(product);
            list.add(product);
        }
        contractProductService.saveList(list); //一次性保存
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;  //重定向到列表数据
    }


}
